package com.ruoyi.yz.controller;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.face.domain.Record;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.yz.domain.YzConference;
import com.ruoyi.yz.service.IYzConferenceService;
import com.ruoyi.yz.service.impl.YzWebsocketService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.yz.domain.YzMember;
import com.ruoyi.yz.service.IYzMemberService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 参会人员Controller
 *
 * @author yz
 * @date 2024-06-14
 */
@Controller
@RequestMapping("/conference/member")
public class YzMemberController extends BaseController
{
    private String prefix = "conference/member";

    @Autowired
    private IYzMemberService yzMemberService;

    @Autowired
    private IYzConferenceService yzConferenceService;

    @Resource
    YzWebsocketService webSocket;

    @Autowired
    private ISysConfigService configService;

    @RequiresPermissions("conference:member:view")
    @GetMapping()
    public String member()
    {
        return prefix + "/member";
    }

    /**
     * 查询参会人员列表
     */
    @RequiresPermissions("conference:member:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(YzMember yzMember)
    {
        startPage();
        List<YzMember> list = yzMemberService.selectYzMemberList(yzMember);
        return getDataTable(list);
    }

    /**
     * 导出参会人员列表
     */
    @RequiresPermissions("conference:member:export")
    @Log(title = "参会人员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(YzMember yzMember)
    {
        List<YzMember> list = yzMemberService.selectYzMemberList(yzMember);
        ExcelUtil<YzMember> util = new ExcelUtil<YzMember>(YzMember.class);
        return util.exportExcel(list, "参会人员数据");
    }

    /**
     * 新增参会人员
     */
    @GetMapping("/add")
    public String add()
    {
        List<YzConference> conferenceList = yzConferenceService.selectYzConferenceList(null);
        Map<Long, String> map = conferenceList.stream().collect(Collectors.toMap(YzConference::getId, YzConference::getName));
        return prefix + "/add";
    }

    /**
     * 检查人员信息是否重复
     */
    @PostMapping("/check")
    @ResponseBody
    public boolean checkUnique(YzMember yzMember) {
        return yzMemberService.checkUnique(yzMember);
    }

    /**
     * 新增保存参会人员
     */
    @Log(title = "参会人员", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated YzMember yzMember)
    {
        return toAjax(yzMemberService.insertYzMember(yzMember));
    }

    /**
     * 修改参会人员
     */
    @RequiresPermissions("conference:member:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        YzMember yzMember = yzMemberService.selectYzMemberById(id);
        mmap.put("yzMember", yzMember);
        return prefix + "/edit";
    }

    /**
     * 修改保存参会人员
     */
    @RequiresPermissions("conference:member:edit")
    @Log(title = "参会人员", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated YzMember yzMember)
    {
        return toAjax(yzMemberService.updateYzMember(yzMember));
    }

    /**
     * 删除参会人员
     */
    @RequiresPermissions("conference:member:remove")
    @Log(title = "参会人员", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(yzMemberService.deleteYzMemberByIds(ids));
    }

    /**
     * 会议报名
     */
    @GetMapping("/signup/{id}")
    public String signup(@PathVariable("id") Long id, ModelMap mmap)
    {
        YzConference conference = yzConferenceService.selectYzConferenceById(id);
        if (conference == null) {
            throw new ServiceException("会议报名地址错误！");
        }
        mmap.put("conference", conference);
        if ("1".equals(conference.getStatus())) {
            mmap.put("message", "报名已结束");

            return prefix + "/signuped";
        }

        return prefix + "/signup";
    }

    /**
     * 会议报名
     */
    @Log(title = "参会人员报名", businessType = BusinessType.INSERT)
    @PostMapping("/signup")
    @ResponseBody
    public AjaxResult signupSave(@Validated YzMember yzMember,  @RequestPart("avatar") MultipartFile file)
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            yzMember.setPhoto(fileName);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return toAjax(yzMemberService.insertYzMember(yzMember));
    }

    /**
     * 会议报名成功
     */
    @GetMapping("/signuped")
    public String signuped(ModelMap mmap)
    {
        mmap.put("message", "您已完成报名!");

        return prefix + "/signuped";
    }

    @Log(title = "管理员手动人员签到", businessType = BusinessType.UPDATE)
    @PostMapping("/manual/{id}")
    @ResponseBody
    public AjaxResult manual(@PathVariable("id") Long id)
    {
        return toAjax(yzMemberService.signIn(id));
    }

    /**
     * 接收设备推送
     */
    @PostMapping("/signin")
    public @ResponseBody void record(@RequestBody Record record) {
        if (!"M014201652308000640".equals(record.getDeviceSn())) {
            logger.error("device unknown: {}", record);
            return;
        }
        if (record.getPersonId() != null && record.getPassType() == 1) {
            logger.info("member sign in by device: {}", record);
            if (yzMemberService.signIn(Long.valueOf(record.getPersonId())) == 1) {
                String message = configService.selectConfigByKey("device.face.notifyMessage");
                if (StringUtils.isEmpty(message)) {
                    message = "参会人员 {name} 通过设备签到";
                }
                webSocket.sendMessage(message.replace("{name}" ,record.getPersonName()));
                logger.info("member sign in success: {}", record);
            }
        } else {
            logger.warn("member sign in failed: {}", record);
        }
    }
}
